<template>
  <div class="card" style="margin-bottom: 5px">
    <div class="card" style="margin-bottom: 5px">
      <el-input v-model="data.name" placeholder="请输入名称查询" style="width: 300px; margin-right: 10px"></el-input>
      <el-button type="primary" @click="load">查询</el-button>
      <el-button type="info" @click="reset">重置</el-button>
      <el-button type="danger" @click="delBatch">批量删除</el-button>
    </div>

    <!--列表展示-->
    <div class="card" style="margin-bottom: 5px">
      <el-table :data="data.tableData" stripe @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center"></el-table-column>
        <el-table-column prop="name" label="名称" />
        <el-table-column prop="cover" label="封面">
          <template #default="scope">
            <el-image :src="scope.row.cover" style="width: 40px; height: 40px; border-radius: 5px"
                      :preview-src-list="[scope.row.cover]" preview-teleported />
          </template>
        </el-table-column>
        <el-table-column prop="descr" label="简介" show-overflow-tooltip />
        <el-table-column prop="director" label="导演" />
        <el-table-column prop="screenwriter" label="编剧" show-overflow-tooltip />
        <el-table-column prop="actors" label="主演" show-overflow-tooltip />
        <el-table-column prop="categoryName" label="类型" />
        <el-table-column prop="country" label="制片国家" />
        <el-table-column prop="language" label="语言" />
        <el-table-column prop="date" label="上映日期" />
        <el-table-column prop="year" label="上映年份" />
        <el-table-column prop="duration" label="片长" />
        <el-table-column prop="imdb" label="IMDb" />
        <el-table-column label="操作" min-width="160">
          <template #default="scope">
            <el-button type="primary" round plain @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="danger" round plain @click="del(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!--分页-->
    <div class="card">
      <el-pagination background layout="->, total, prev, pager, next" v-model:current-page="data.pageNum" v-model:page-size="data.pageSize"
                     :total="data.total" @current-change="load" />
    </div>

    <!--弹窗-->
    <el-dialog v-model="data.formVisible" title="电影信息" width="40%">
      <el-form ref="ruleFormRef" :model="data.form" :rules="rules" label-width="80px" style="padding-right: 20px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="data.form.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="封面" prop="cover">
          <el-upload v-model="data.form.cover" ref="uploadRef" :action="uploadUrl" list-type="picture" :on-success="handleImgSuccess" :limit="1" :on-exceed="handleExceed">
            <el-button type="primary">上传图片</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="简介" prop="descr">
          <el-input :rows="5" type="textarea" v-model="data.form.descr" autocomplete="off" placeholder="请输入电影简介" />
        </el-form-item>
        <el-form-item label="导演" prop="director">
          <el-input v-model="data.form.director" autocomplete="off" placeholder="请输入导演" />
        </el-form-item>
        <el-form-item label="编剧" prop="screenwriter">
          <el-input v-model="data.form.screenwriter" autocomplete="off" placeholder="请输入编剧" />
        </el-form-item>
        <el-form-item label="主演" prop="actors">
          <el-input :rows="4" type="textarea" v-model="data.form.actors" autocomplete="off" placeholder="请输入主演" />
        </el-form-item>
        <el-form-item label="类型" prop="categoryName">
          <el-radio-group v-for="item in data.categoryForm" :key="item.id" v-model="data.form.categoryName" @change="changeCategoryId">
            <el-radio style="margin-right: 20px;" :label=item.id>{{ item.name }}</el-radio>
          </el-radio-group>
          <el-popover :visible="data.addCategoryVisible" placement="right" :width="150">
            <el-input v-model="data.categoryName.name" autocomplete="off" placeholder="请输入类型名称" />
            <div style="margin-top: 10px;">
              <el-button size="small" text @click="data.addCategoryVisible = false">取消</el-button>
              <el-button size="small" type="primary" @click="addCategory">确定</el-button>
            </div>
            <template #reference>
              <el-button @click="data.addCategoryVisible = true">添加类型</el-button>
            </template>
          </el-popover>
        </el-form-item>
        <el-form-item label="国家" prop="country">
          <el-input v-model="data.form.country" autocomplete="off" placeholder="请输入制片国家" />
        </el-form-item>
        <el-form-item label="语言" prop="language">
          <el-input v-model="data.form.language" type="language" autocomplete="off" placeholder="请输入语言" />
        </el-form-item>
        <el-form-item label="上映日期" prop="date">
          <el-date-picker style="width: 100%" type="date" v-model="data.form.date" placeholder="请选择上映日期" format="YYYY-MM-DD" value-format="YYYY-MM-DD"></el-date-picker>
        </el-form-item>
        <el-form-item label="上映年份" prop="year">
          <el-date-picker style="width: 100%" type="year" v-model="data.form.year" placeholder="请选择上映年份" format="YYYY年" value-format="YYYY年"></el-date-picker>
        </el-form-item>
        <el-form-item label="片长" prop="duration">
          <el-input v-model="data.form.duration" autocomplete="off" placeholder="请输入片长" />
        </el-form-item>
        <el-form-item label="IMDb" prop="imdb">
          <el-input v-model="data.form.imdb" autocomplete="off" placeholder="请输入IMDb" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="data.formVisible = false">取 消</el-button>
          <el-button plain type="primary" @click="save">保 存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template> <script setup>
import { reactive, ref } from "vue";
import request from "@/utils/request";
import {ElMessage, ElMessageBox} from "element-plus";

const data = reactive({
  tableData: [],
  total: 0,
  pageNum: 1,
  pageSize: 10,
  name: null,
  formVisible: false,
  form: {},
  categoryForm: {},
  categoryName: {},
  user: JSON.parse(localStorage.getItem('system-user') || '{}'),
  addCategoryVisible: false,
})

//新增校验规则
const ruleFormRef = ref(null)
const rules = {
  name: [{ required: true, message: '电影名称不能为空', trigger: 'blur' }],
  cover: [{ required: true, message: '未上传电影封面', trigger: 'blur' }],
  descr: [{ required: true, message: '电影简介不能为空', trigger: 'blur' }],
  screenwriter: [{ required: true, message: '电影编剧不能为空', trigger: 'blur' }],
  director: [{ required: true, message: '电影拍摄导演不能为空', trigger: 'blur' }],
  actors: [{ required: true, message: '电影主演不能为空', trigger: 'blur' }],
  categoryName: [{ required: true, message: '必须选择一个类型', trigger: 'change' }],
  country: [{ required: true, message: '电影制片国家不能为空', trigger: 'blur' }],
  language: [{ required: true, message: '电影语言不能为空', trigger: 'blur' }],
  date: [{ required: true, message: '未选择电影上映日期', trigger: 'blur' }],
  year: [{ required: true, message: '未选择电影上映年份', trigger: 'blur' }],
  duration: [{ required: true, message: '电影片长不能为空', trigger: 'blur' },
    { pattern: /^\d+分钟$/, message: '请输入以“分钟”结尾的片长', trigger: 'blur' }],
  imdb: [{ required: true, message: '电影IMDb值不能为空', trigger: 'blur' }],
}

const load = () => {
  request.get('/film/selectPage', {
    params: {
      pageNum: data.pageNum,
      pageSize: data.pageSize,
      name: data.name,
      userId: data.user.role === 'ADMIN' ? null : data.user.id
    }
  }).then(res => {
    data.tableData = res.data?.list
    data.total = res.data?.total
  })
}
load() // 设置类型id，保存类型名称

const changeCategoryId = (val) => {
  data.form.categoryId = val
}

// 查询类型
const loadCategory = () => {
  request.get('/category/selectAll').then(res => {
    data.categoryForm = res.data
  })
  console.log(data.categoryForm)
}

// 新增类型名
const addCategory = () =>{
  if(!data.categoryName.name){
    ElMessage.error('请输入类型名称')
  }else{
    request.post('/category/add', data.categoryName).then((res) => {
      if(res.code === '200'){
        loadCategory()
        data.addCategoryVisible = false
        ElMessage.success('操作成功')
      }else{
        ElMessage.error(res.msg)
      }
    })
  }
}

// 编辑
const handleEdit = (row) => {
  loadCategory()
  data.form = JSON.parse(JSON.stringify(row))
  data.formVisible = true
}
// 编辑保存
const save = () => {
  if (!ruleFormRef.value) return;
  ruleFormRef.value.validate((valid) => {
    if (valid) {
      request.put('/film/update', data.form).then(res => {
        if (res.code === '200') {
          load()
          data.formVisible = false
          ElMessage.success('操作成功')
        } else {
          ElMessage.error(res.msg)
        }
      })
    } else {
      ElMessage.error('请填写必填项')
    }
  })
}

// 删除
const del = (id) => {
  ElMessageBox.confirm('删除数据后无法恢复，确认删除吗？', '确认删除', { type: 'warning' }).then(res => {
    request.delete('/film/delete/' + id).then(res => {
      if (res.code === '200') {
        request.delete('/comment/deleteComment/' + id).then(res => {
          if(res.code === '200'){
            load()
            ElMessage.success('操作成功')
          }else{
            ElMessage.error(res.msg)
          }
        })
      } else {
        ElMessage.error(res.msg)
      }
    })
  }).catch(err => {})
}

// 批量删除
const handleSelectionChange = (rows) => {
  data.ids = rows.map(row => row.id)
}
const delBatch = () => {
  if(!data.ids){
    ElMessage.error('请选择要删除的数据')
  }else{
    ElMessageBox.confirm('删除后无法恢复，确定要删除吗？', '确认删除', {type: "warning"}).then(res => {
      request.delete('/film/delete-batch' , {data:data.ids}).then(res => {
        if (res.code === '200') {
          load()
          ElMessage.success('操作成功')
        } else {
          ElMessage.error(res.msg)
        }
      })
    }).catch(err => {
    })
  }
}

// 重置
const reset = () => {
  data.name = null
  load()
}

// 文件上传的接口地址
const uploadUrl = import.meta.env.VITE_BASE_URL + '/files/upload'
const uploadRef = ref(null);
// 处理文件上传的钩子
const handleImgSuccess = (res) => {
  data.form.cover = res.data  // res.data就是文件上传返回的文件路径，获取到路径后赋值表单的属性
}

// 生成UID
const genFileId = () => Math.random().toString(36).substring(7);

// 限制上传头像数量
const handleExceed = (files, fileList) => {
  const upload = uploadRef.value;
  if (upload) {
    upload.clearFiles();
    const file = files[0];
    file.uid = genFileId();
    upload.handleStart(file);
  }
}
</script>